package fi.tikesos.validator.jena.rdfa;

import java.io.InputStream;
import java.io.Reader;

import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFErrorHandler;
import com.hp.hpl.jena.rdf.model.RDFReader;

import fi.tikesos.rdfa.core.parser.RDFaParser;
import fi.tikesos.rdfa.core.parser.sax.SAXRDFaParser;
import fi.tikesos.rdfa.core.triple.TripleSink;
import org.xml.sax.SAXParseException;


public class RDFaReaderImpl implements RDFReader {
	RDFErrorHandler errorHandler;

	@Override
	public void read(Model model, InputStream r, String base) {
		// Default method
		XMLReader reader;
		try {
			reader = XMLReaderFactory.createXMLReader();
			reader.setFeature("http://xml.org/sax/features/validation",
					Boolean.TRUE);
			reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
					Boolean.TRUE);
			reader.setEntityResolver(new LocalEntityResolver());
			//new NullEntityResolver()
			try {
				TripleSink sink = new JenaTripleSink(model);
				ContentHandler parser = new SAXRDFaParser(base, sink, null,
						null, RDFaParser.XML_RDFA);
				reader.setContentHandler(parser);
				reader.parse(new InputSource(r));
			} catch (SAXParseException e) {
				if (errorHandler != null) {
					errorHandler.fatalError(e);
				}
				//e.printStackTrace();
			}
		} catch (Exception e) {
			if (errorHandler != null) {
				errorHandler.fatalError(e);
			}
		}
	}

	@Override
	public void read(Model model, Reader r, String base) {
		// Not implemented
		if (errorHandler != null) {
			errorHandler.fatalError(new NoSuchMethodException(
					"Method has not been implemented"));
		}
	}

	@Override
	public void read(Model model, String url) {
		// Not implemented
		if (errorHandler != null) {
			errorHandler.fatalError(new NoSuchMethodException(
					"Method has not been implemented"));
		}
	}

	@Override
	public Object setProperty(String propName, Object propValue) {
		// Set reader property
		return null;
	}

	@Override
	public RDFErrorHandler setErrorHandler(RDFErrorHandler errorHandler) {
		// TODO Auto-generated method stub
		RDFErrorHandler oldErrorHandler = errorHandler;
		this.errorHandler = errorHandler;
		return oldErrorHandler;
	}
}
